package cn.lingnan.Interceptor;

import cn.lingnan.utils.JwtUtils;
import cn.lingnan.utils.Result;
import com.alibaba.fastjson.JSONObject;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component

public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        log.info("请求 URL: {}", url);

        // Allow login requests to pass through without checking the token
        if (url.contains("login")||url.contains("register")) {
            log.info("这是一个登录请求");
            return true;
        }

        // Retrieve the token from the request header
        String jwt = request.getHeader("Authorization");
        log.info("Token: {}", jwt);
        if (jwt != null && jwt.startsWith("Bearer ")) {
            jwt = jwt.substring(7); // 移除 "Bearer "前缀
        }

        // 检查令牌是否为空
        if (!StringUtils.hasLength(jwt)) {
            log.info("令牌为空");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            Result error = Result.error("没有登录");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        // 解析令牌
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            log.error("无法解析令牌", e);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            Result error = Result.error("令牌无效");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        log.info("令牌有效");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // This can be used for additional processing after the request has been handled
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // This can be used for cleanup after the request has been completed
    }
}
